/**
 *  This program is free software; you can redistribute it and/or modify it under 
 *  the terms of the GNU General Public License as published by the Free Software 
 *  Foundation; either version 3 of the License, or (at your option) any later 
 *  version.
 *  You should have received a copy of the GNU General Public License along with 
 *  this program; if not, see <http://www.gnu.org/licenses/>. 
 *  Use this application at your own risk.
 *
 *  Copyright (c) 2009 by Michael Münch.
 */

package eu.micm.android.tvprogramm;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

import android.app.*;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.*;
import android.view.Menu;
import android.widget.*;

public class TVProgramm extends ListActivity {

    public static final int MReload = Menu.FIRST + 1;

    public static final int MAbout = Menu.FIRST + 3;

    public static final int MBrowser = Menu.FIRST + 2;

    public void populateMenu(Menu menu) {
        MenuItem item1 = menu.add(0, MReload, 0, "Reload");
        MenuItem item2 = menu.add(0, MBrowser, 0, "Browser");
        MenuItem item3 = menu.add(0, MAbout, 0, "About");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        populateMenu(menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return applyMenuChoice(item) || super.onOptionsItemSelected(item);
    }

    public boolean applyMenuChoice(MenuItem item) {
        switch (item.getItemId()) {
        case MReload:
            Intent iReload = new Intent(TVProgramm.this, TVProgramm.class);
            Bundle bReload = this.getIntent().getExtras();
            iReload.putExtras(bReload);
            startActivity(iReload);
            return true;
        case MAbout:
            final AlertDialog about = new AlertDialog.Builder(TVProgramm.this).create();
            about.setTitle("About");
            about.setMessage(getString(R.string.about));
            about.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    about.dismiss();
                }
            });
            about.show();
            return true;
        case MBrowser:
            String surl = "http://tv.intern.de";
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(surl)));
            return true;
        }
        return false;
    }

    static final private int SENDUNG_DIALOG = 1;

    ArrayList<HashMap<String, String>> programm = new ArrayList<HashMap<String, String>>();

    String title, date, link, description;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        Bundle b = this.getIntent().getExtras();
        String surl = b.getString("url");
        System.out.println(surl);
        getFeed(surl);
        BaseAdapter adapter = new SimpleAdapter(this, programm, R.layout.list_item, new String[] {
                "title", "date" }, new int[] { R.id.title, R.id.date });
        setListAdapter(adapter);

    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        title = programm.get(position).get("title");
        date = programm.get(position).get("date");
        link = programm.get(position).get("link");
        description = programm.get(position).get("description");
        showDialog(SENDUNG_DIALOG);
    }

    @Override
    public Dialog onCreateDialog(int id) {
        switch (id) {
        case (SENDUNG_DIALOG):
            LayoutInflater li = LayoutInflater.from(this);
            View DetailView = li.inflate(R.layout.detail, null);
            AlertDialog.Builder sendungDialog = new AlertDialog.Builder(this);
            sendungDialog.setTitle(title);
            sendungDialog.setView(DetailView);
            return sendungDialog.create();
        }
        return null;
    }

    @Override
    public void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case (SENDUNG_DIALOG):
            String sendungText = "Title " + title + "\n" + description;

            AlertDialog sendungDialog = (AlertDialog) dialog;
            sendungDialog.setTitle(title);

            TextView tv = (TextView) sendungDialog.findViewById(R.id.DetailTextView);
            if (tv != null) tv.setText(sendungText);
            break;
        }
    }

    private void getFeed(String surl) {
        try {
            URL url = new URL(surl);

            URLConnection connection = url.openConnection();

            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = httpConnection.getInputStream();

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();

                Document dom = db.parse(in);
                Element docEle = dom.getDocumentElement();

                programm.clear();

                NodeList nl = docEle.getElementsByTagName("item");
                System.out.println("getLength(): " + nl.getLength());
                if (nl != null && nl.getLength() > 0) {
                    for (int i = 0; i < nl.getLength(); i++) {
                        Element eitem = (Element) nl.item(i);
                        Element etitle = (Element) eitem.getElementsByTagName("title").item(0);
                        Element elink = (Element) eitem.getElementsByTagName("link").item(0);
                        Element edescription = (Element) eitem.getElementsByTagName("description")
                                .item(0);
                        String sdate = "";
                        String sdescription = edescription.getFirstChild().getNodeValue();
                        String pattern = "(\\d\\d\\.\\d\\d\\.\\d\\d um \\d\\d\\:\\d\\d Uhr)";
                        Matcher matcher = Pattern.compile(pattern).matcher(sdescription);
                        while (matcher.find()) {
                            sdate = matcher.group(1);
                        }
                        String stitle = etitle.getFirstChild().getNodeValue();
                        System.out.println("title: " + title);
                        String slink = elink.getFirstChild().getNodeValue();

                        HashMap<String, String> sendung = new HashMap<String, String>();
                        sendung.put("title", stitle);
                        sendung.put("date", sdate);
                        sendung.put("link", slink);
                        sendung.put("description", sdescription);
                        programm.add(sendung);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
